package city.spring.modules.material.controller;

import city.spring.modules.material.entity.MaterialBreakageWarehouseMaterialExtEntity;
import city.spring.modules.material.repository.MaterialBreakageWarehouseMaterialExtRepository;
import city.spring.modules.material.service.MaterialBreakageWarehouseMaterialExtService;
import city.spring.utils.MyBatisUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Controller：部门报损关联物资表
 *
 * @author 谢金婷
 * @date 2021-01-18 11:09:09
 */
@RestController
@RequestMapping("/material_breakage_warehouse/{breakageId}/material")
public class MaterialBreakageWarehouseMaterialExtController extends ApiController {
    private final MaterialBreakageWarehouseMaterialExtService materialBreakageWarehouseMaterialExtService;
    private final MaterialBreakageWarehouseMaterialExtRepository materialBreakageWarehouseMaterialExtRepository;
    /**
     * 实体类可排序字段
     */
    private final List<SFunction<MaterialBreakageWarehouseMaterialExtEntity, ?>> entityOrderFields;

    public MaterialBreakageWarehouseMaterialExtController(MaterialBreakageWarehouseMaterialExtService materialBreakageWarehouseMaterialExtService, MaterialBreakageWarehouseMaterialExtRepository materialBreakageWarehouseMaterialExtRepository) {
        this.materialBreakageWarehouseMaterialExtService = materialBreakageWarehouseMaterialExtService;
        this.materialBreakageWarehouseMaterialExtRepository = materialBreakageWarehouseMaterialExtRepository;
        entityOrderFields = new ArrayList<>();
        entityOrderFields.add(MaterialBreakageWarehouseMaterialExtEntity::getId);
        entityOrderFields.add(MaterialBreakageWarehouseMaterialExtEntity::getBreakageId);
        entityOrderFields.add(MaterialBreakageWarehouseMaterialExtEntity::getMaterialId);
        entityOrderFields.add(MaterialBreakageWarehouseMaterialExtEntity::getBreakageQuantity);
        entityOrderFields.add(MaterialBreakageWarehouseMaterialExtEntity::getBreakageTotal);
        entityOrderFields.add(MaterialBreakageWarehouseMaterialExtEntity::getReason);
    }

    @ModelAttribute
    public void getBreakageId(@PathVariable String breakageId) {
        if (breakageId == null) {
            throw new RuntimeException("报损单ID必须不为空");
        }
        System.out.println("breakageId" + breakageId);
    }

    /**
     * 获取全部的 <strong>部门报损关联物资表</strong> 列表
     */
    @GetMapping("all")
    public Object listAll(@PageableDefault Pageable pageable, MaterialBreakageWarehouseMaterialExtEntity entity) {
        LambdaQueryChainWrapper<MaterialBreakageWarehouseMaterialExtEntity> lambdaQuery = buildLambdaQuery(entity);
        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
        return success(lambdaQuery.list());
    }

    //    /**
//     * 分页获取 <strong>部门报损关联物资表</strong> 列表
//     *
//     * @param pageable 分页参数信息
//     */
//    @GetMapping
//    public Object list(@PageableDefault Pageable pageable, MaterialBreakageWarehouseMaterialExtEntity entity) {
//        LambdaQueryChainWrapper<MaterialBreakageWarehouseMaterialExtEntity> lambdaQuery = buildLambdaQuery(entity);
//        MyBatisUtils.lambdaQueryAddOrder(lambdaQuery, pageable, entityOrderFields);
//        Page<MaterialBreakageWarehouseMaterialExtEntity> page = lambdaQuery.page(MyBatisUtils.toPage(pageable, false));
//        return success(page);
//    }
    @GetMapping
    public Object list(@PathVariable String breakageId) {
        return success(materialBreakageWarehouseMaterialExtRepository.getWarehousingMaterials(breakageId));
    }

    //
//    /**
//     * 获取一个 <strong>部门报损关联物资表</strong>
//     *
//     * @param id 主键ID
//     */
//    @GetMapping("{id}")
//    public Object info(@PathVariable String id) {
//        return success(materialBreakageWarehouseMaterialExtService.getById(id));
//    }
    @GetMapping("{extId}")
    public Object getInfo(@PathVariable String breakageId, @PathVariable String extId) {
        return success(materialBreakageWarehouseMaterialExtRepository.getWarehousingMaterial(breakageId, extId));
    }

    //    /**
//     * 添加一个 <strong>部门报损关联物资表</strong>
//     *
//     * @param entity 修改后的信息
//     */
//    @PostMapping
//    public Object add(@RequestBody MaterialBreakageWarehouseMaterialExtEntity entity) {
//        materialBreakageWarehouseMaterialExtService.saveMaterialBreakageWarehouseMaterialExt(entity);
//
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.LOCATION, String.valueOf(entity.getId()));
//        return new ResponseEntity<>(headers, HttpStatus.CREATED);
//    }

    /**
     * @param breakageId
     * @param materials
     * @return
     */
    @PostMapping
    public Object addAll(@PathVariable String breakageId, @RequestBody List<MaterialBreakageWarehouseMaterialExtEntity> materials) {

        // 查出已有的数据
        List<MaterialBreakageWarehouseMaterialExtEntity> dbMaterials = materialBreakageWarehouseMaterialExtRepository.getWarehousingMaterials(breakageId);

        // 数据库已经存在的物资列表
        Set<String> dbMaterialIdsSet = dbMaterials.stream()
                .map(MaterialBreakageWarehouseMaterialExtEntity::getMaterialId)
                .collect(Collectors.toSet());
        // 过滤掉已经存在数据库的数据
        List<MaterialBreakageWarehouseMaterialExtEntity> needSaveMaterials = materials.stream()
                .filter(item -> {
                    item.setBreakageId(breakageId);
                    item.setBreakageTotal(item.getBreakageQuantity().multiply(item.getUnitprice()));
                    String materialId = item.getMaterialId();
                    // 过滤出不存在数据库中的数据
                    return materialId != null && !dbMaterialIdsSet.contains(materialId);
                }).collect(Collectors.toList());

        if (!needSaveMaterials.isEmpty()) {
            materialBreakageWarehouseMaterialExtService.saveBatch(needSaveMaterials);
        }

        return success(null);
    }

//    /**
//     * 修改一个 <strong>部门报损关联物资表</strong>
//     *
//     * @param id     主键ID
//     * @param entity 修改后的信息
//     */
//    @PutMapping("{id}")
//    public Object update(@PathVariable String id, @RequestBody MaterialBreakageWarehouseMaterialExtEntity entity) {
//        entity.setId(id);
//        materialBreakageWarehouseMaterialExtService.updateMaterialBreakageWarehouseMaterialExt(entity);
//        return new ResponseEntity<>(HttpStatus.OK);
//    }

    @PutMapping("{extId}")
    public Object update(@PathVariable String breakageId, @PathVariable String extId, @RequestBody MaterialBreakageWarehouseMaterialExtEntity extEntity) {
        extEntity.setId(extId);
        extEntity.setBreakageId(breakageId);
        materialBreakageWarehouseMaterialExtService.updateMaterialBreakageWarehouseMaterialExt(extEntity);
        return success(null);
    }

    /**
     * 删除一个 <strong>部门报损关联物资表</strong>
     *
     * @param id 主键ID
     */
    @DeleteMapping("{id}")
    public Object delete(@PathVariable String id) {
        materialBreakageWarehouseMaterialExtService.deleteMaterialBreakageWarehouseMaterialExt(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 删除多个 <strong>部门报损关联物资表</strong>
     *
     * @param ids 主键ID列表
     */
    @DeleteMapping
    public Object deleteIds(@RequestBody List<String> ids) {
        materialBreakageWarehouseMaterialExtService.deleteMaterialBreakageWarehouseMaterialExt(ids);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private LambdaQueryChainWrapper<MaterialBreakageWarehouseMaterialExtEntity> buildLambdaQuery(MaterialBreakageWarehouseMaterialExtEntity entity) {
        LambdaQueryChainWrapper<MaterialBreakageWarehouseMaterialExtEntity> lambdaQuery = materialBreakageWarehouseMaterialExtService.lambdaQuery();
        lambdaQuery.eq(StringUtils.isNotBlank(entity.getId()), MaterialBreakageWarehouseMaterialExtEntity::getId, entity.getId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getBreakageId()), MaterialBreakageWarehouseMaterialExtEntity::getBreakageId, entity.getBreakageId());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getMaterialId()), MaterialBreakageWarehouseMaterialExtEntity::getMaterialId, entity.getMaterialId());
        lambdaQuery.eq(entity.getBreakageQuantity() != null, MaterialBreakageWarehouseMaterialExtEntity::getBreakageQuantity, entity.getBreakageQuantity());
        lambdaQuery.eq(entity.getBreakageTotal() != null, MaterialBreakageWarehouseMaterialExtEntity::getBreakageTotal, entity.getBreakageTotal());
        lambdaQuery.like(StringUtils.isNotBlank(entity.getReason()), MaterialBreakageWarehouseMaterialExtEntity::getReason, entity.getReason());
        return lambdaQuery;
    }

    /**
     * 构建查询条件内容
     *
     * @param entity 实体对象
     * @return lambda query chain wrapper
     */
    private QueryWrapper<MaterialBreakageWarehouseMaterialExtEntity> buildQuery(MaterialBreakageWarehouseMaterialExtEntity entity) {
        QueryWrapper<MaterialBreakageWarehouseMaterialExtEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StringUtils.isNotBlank(entity.getId()), "id", entity.getId());
        wrapper.like(StringUtils.isNotBlank(entity.getBreakageId()), "breakage_id", entity.getBreakageId());
        wrapper.like(StringUtils.isNotBlank(entity.getMaterialId()), "material_id", entity.getMaterialId());
        wrapper.eq(entity.getBreakageQuantity() != null, "breakage_quantity", entity.getBreakageQuantity());
        wrapper.eq(entity.getBreakageTotal() != null, "breakage_total", entity.getBreakageTotal());
        wrapper.like(StringUtils.isNotBlank(entity.getReason()), "reason", entity.getReason());
        return wrapper;
    }

}
